package com.cskaoyan.batch;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 创建日期: 2022/06/30 15:02
 *
 * @author ciggar
 */
public class BatchDemo {

    static Connection connection;

    static {
        connection = JDBCUtils.getConnection();
    }

    public static void main(String[] args) throws SQLException {

//        long  t1= System.currentTimeMillis();
//        forEachInsert(10000);
//        long  t2= System.currentTimeMillis();
//        statementBatch(10000);
        long  t3= System.currentTimeMillis();
        preparedStatementBatch(10000000);
        long  t4= System.currentTimeMillis();

//        System.out.println("foreach循环的时间：" + (t2-t1) + " 毫秒");
//        System.out.println("statement的时间：" + (t3-t2) + " 毫秒");
        System.out.println("PreparedStatement的时间：" + (t4-t3) + " 毫秒");


    }



    // for循环逐条插入
    public static void forEachInsert(int count) throws SQLException {

        for (int i = 0; i < count; i++) {
            String username = "foreach:" + i;
            Statement statement = connection.createStatement();
            String sql = "insert into user values (null,'"+username+"',null)";

            statement.executeUpdate(sql);
            statement.close();
        }
    }

    // statement进行批处理
    public static void statementBatch(int count) throws SQLException {

        // 获取Statement
        Statement statement = connection.createStatement();

        for (int i = 0; i < count; i++) {
            String username = "statementBatch:" + i;
            String sql = "insert into user values (null,'"+username+"',null)";

            // 往Statement里面添加SQL语句(类似于往小拖车里面添加砖头)
            statement.addBatch(sql);
        }
        // 执行SQL语句
        statement.executeBatch();

        statement.close();


    }



    // PreparedStatement进行批处理
    public static void preparedStatementBatch(int count) throws SQLException {

        // 获取PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement("insert into user values (null,?,null)");


        // 批处理
        for (int i = 0; i < count; i++) {

            String username = "preparedStatementBatch:" + i;

            // 设置参数
            preparedStatement.setString(1,username);

            preparedStatement.addBatch();
        }
        // 执行
        preparedStatement.executeBatch();

        preparedStatement.close();


    }


}
